import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'
import AliyunTextRewriter from '@/lib/aliyunTextRewriter'

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const user = await getUserFromRequest(request)
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const {
      extractionIds,
      prompt
    } = await request.json()

    if (!extractionIds || !Array.isArray(extractionIds) || extractionIds.length === 0) {
      return NextResponse.json(
        { error: '请选择要改写的文案' },
        { status: 400 }
      )
    }

    if (!prompt || !prompt.trim()) {
      return NextResponse.json(
        { error: '请输入改写提示词' },
        { status: 400 }
      )
    }

    console.log(`🚀 开始批量改写文案，文案数量: ${extractionIds.length}`)
    console.log('💬 改写提示词:', prompt)

    // 获取选中的文案提取记录
    const textExtractions = await prisma.textExtraction.findMany({
      where: {
        id: { in: extractionIds },
        status: 'completed'
      },
      include: {
        video: {
          select: {
            id: true,
            videoId: true,
            title: true
          }
        }
      }
    })

    if (textExtractions.length === 0) {
      return NextResponse.json(
        { error: '未找到选中的文案记录' },
        { status: 404 }
      )
    }

    // 过滤出有有效文案的记录
    const validExtractions = textExtractions.filter(extraction => 
      extraction.extractedText && 
      extraction.extractedText.trim().length > 0
    )

    if (validExtractions.length === 0) {
      return NextResponse.json(
        { error: '选中的文案都无有效内容' },
        { status: 400 }
      )
    }

    console.log(`📝 找到 ${validExtractions.length} 个有效文案`)

    // 立即返回响应，告知用户改写已开始
    const response = NextResponse.json({
      success: true,
      message: `改写任务已启动，正在后台处理 ${validExtractions.length} 个文案的改写`,
      taskStarted: true,
      itemsCount: validExtractions.length
    })

    // 在后台异步执行改写任务
    setImmediate(async () => {
      console.log('🔄 开始后台文案改写任务...')
      
      // 初始化文案改写服务
      const rewriter = new AliyunTextRewriter()
      
      // 逐个改写文案
      for (const extraction of validExtractions) {
        try {
          console.log(`🎯 开始改写文案 ${extraction.id} (视频: ${extraction.video.videoId})`)
          console.log(`📄 原文案: ${extraction.extractedText.substring(0, 100)}${extraction.extractedText.length > 100 ? '...' : ''}`)
          
          const rewriteResult = await rewriter.rewriteText({
            originalText: extraction.extractedText,
            prompt
          })

          if (rewriteResult.success && rewriteResult.rewrittenText) {
            // 检查是否已有改写记录，如果有则更新，没有则创建
            const existingRewrite = await prisma.rewrittenText.findFirst({
              where: {
                originalTextId: extraction.id
              }
            })

            if (existingRewrite) {
              // 更新现有记录
              await prisma.rewrittenText.update({
                where: { id: existingRewrite.id },
                data: {
                  rewrittenText: rewriteResult.rewrittenText,
                  style: 'custom',
                  tone: 'custom',
                  length: 'custom',
                  requirements: prompt,
                  requestId: rewriteResult.requestId || '',
                  updatedAt: new Date()
                }
              })
              console.log(`✅ 更新文案 ${extraction.id} 的改写记录`)
            } else {
              // 创建新记录
              await prisma.rewrittenText.create({
                data: {
                  videoId: extraction.videoId,
                  originalTextId: extraction.id,
                  originalText: extraction.extractedText,
                  rewrittenText: rewriteResult.rewrittenText,
                  style: 'custom',
                  tone: 'custom',
                  length: 'custom',
                  requirements: prompt,
                  requestId: rewriteResult.requestId || '',
                  createdBy: user.id
                }
              })
              console.log(`✅ 创建文案 ${extraction.id} 的改写记录`)
            }

            console.log(`📝 改写结果: ${rewriteResult.rewrittenText.substring(0, 100)}${rewriteResult.rewrittenText.length > 100 ? '...' : ''}`)
          } else {
            console.log(`❌ 文案 ${extraction.id} 改写失败: ${rewriteResult.error}`)
          }
        } catch (error) {
          console.error(`💥 文案 ${extraction.id} 改写异常:`, error)
        }

        // 添加延迟避免API限制
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
      
      console.log('🎉 后台文案改写任务全部完成！')
    })

    return response

  } catch (error) {
    console.error('❌ 批量改写文案失败:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : '改写失败' },
      { status: 500 }
    )
  }
}
